'use client';

import { useAuth } from '@clerk/nextjs';
import { observer } from 'mobx-react-lite';
import { usePathname, useSearchParams } from 'next/navigation';
import React, { useCallback, useEffect, useRef, useState } from 'react';
import { useIntersectionObserver } from 'usehooks-ts';

import { useStores } from '@/app/(root)/AppProviders';
import { ModalTypes } from '@/components/modal/constants/ModalTypes';
import {
  SunoShortType,
  getSunoShortType,
  tagsToArray,
  tagsToNegativeTags,
} from '@/components/song/songUtils';
import { useMobileBanner } from '@/context/MobileBannerContext';
import { useModalContext } from '@/context/ModalContext';
import { usePreviewContext } from '@/context/PreviewContext';
import { useBreakpointMd } from '@/hooks/useBreakpoint';
import { useMobileLayoutAwareHeight } from '@/hooks/useDynamicViewportHeight';
import usePageViewLog from '@/hooks/usePageViewLog';
import { usePlaybarStatusForClip } from '@/hooks/usePlaybar';
import { ContextType } from '@/logging/contextTypes';
import type SongPageEventType from '@/logging/eventTypes/SongPageEventType';
import logWebUserEvent from '@/logging/logWebUserEvent';
import { Clip, isLiked } from '@/state/clipStore';
import { Persona, PersonaMetadata } from '@/state/personaStore';
import { getClipTitle } from '@/utils/clip';
import { SIGNUP_SOURCE_PARAM, SIGNUP_SOURCE_VALUES } from '@/utils/constants';
import { isMobileBrowser } from '@/utils/device';
import { shareClip } from '@/utils/download';
import { isSecretStatsProfile } from '@/utils/utils';

// 30 seconds
import MobileSongPageHeader from './MobileSongPageHeader';
import SongPageSkeleton from './SongPageSkeleton';

const JOIN_SUNO_MODAL_DELAY = 30000; // 30 seconds

type Props = {
  clip: Clip;
  persona?: PersonaMetadata | Persona | null;
  clipHistoryIds?: string[];
};

const MobileSongPage: React.FC<Props> = observer(
  ({ clip, persona: preloadPersona }: Props) => {
    const { isBannerVisible } = useMobileBanner();
    const { style: dynamicHeightStyle } =
      useMobileLayoutAwareHeight(isBannerVisible);

    const {
      clips,
      playbar,
      session,
      // contest: contestStore,
      queue: queueStore,
    } = useStores();

    const { setClipForSongRecs, setPreviewClip, setAllowFlushToTop } =
      usePreviewContext();

    const { openModalWithData } = useModalContext();
    const { isSignedIn } = useAuth();

    const pathname = usePathname();
    const searchParams = useSearchParams();
    const joinSunoModalShown = useRef(false);
    const timerRef = useRef<NodeJS.Timeout | null>(null);

    // Auto-open modal after 30 seconds for logged out users
    useEffect(() => {
      // Don't show modal if user is already signed in
      if (isSignedIn) {
        return;
      }

      // Don't start timer if modal already shown
      if (joinSunoModalShown.current) {
        return;
      }

      // Show modal after 30 seconds
      timerRef.current = setTimeout(() => {
        if (joinSunoModalShown.current) {
          return; // Don't show if already shown via other means
        }

        // Don't interrupt if user is typing in an input field
        const activeElement = document.activeElement;
        if (
          activeElement &&
          (activeElement.tagName === 'INPUT' ||
            activeElement.tagName === 'TEXTAREA' ||
            (activeElement as HTMLElement).contentEditable === 'true')
        ) {
          return;
        }

        const defaultRedirectUrl = `${pathname}?${SIGNUP_SOURCE_PARAM}=${SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE}&${searchParams.toString()}`;
        openModalWithData(ModalTypes.JOIN_SUNO, {
          clipId: clip.id,
          redirectUrl: defaultRedirectUrl,
        });
        joinSunoModalShown.current = true;
      }, JOIN_SUNO_MODAL_DELAY);

      return () => {
        if (timerRef.current) {
          clearTimeout(timerRef.current);
        }
      };
    }, [isSignedIn, clip.id, openModalWithData]); // Removed defaultRedirectUrl from dependencies

    // const statsigClient = useStatsigClient();

    // Get play status for this clip
    const { isCurrentSong, isPlaying } = usePlaybarStatusForClip(clip.id, {
      contextId: clip.id,
      contextType: ContextType.Song,
    });

    const commentCount =
      clips.clipById[clip.id]?.comment_count || clip.comment_count || undefined;

    // const showComments = searchParams.get('show_comments') === 'true';
    // const [currentTab, setCurrentTab] = useState<'lyrics' | 'comments'>(
    //   showComments ? 'comments' : 'lyrics'
    // );
    // const tabs = useMemo(
    //   () =>
    //     [
    //       { id: 'lyrics', label: t('song.lyrics') } as const,
    //       {
    //         id: 'comments',
    //         label: commentCount
    //           ? `${t('song.comments')} (${getCountString(commentCount, true)})`
    //           : t('song.comments'),
    //       } as const,
    //     ].filter((tab): tab is Exclude<typeof tab, null> => tab !== null),
    //   [commentCount]
    // );

    const [liked, setLiked] = useState(false);
    const [clipTitle, setClipTitle] = useState(getClipTitle(clip));
    const [newClipTitle, setNewClipTitle] = useState(clipTitle);
    const [upvoteCount, setUpvoteCount] = useState(clip?.upvote_count);
    // const [lyrics, setLyrics] = useState(clip.metadata?.prompt || '');

    // const enableSunoScenesBadge =
    //   statsigClient.checkGate(SUNO_SCENES_UI_FEATURE_FLAG) &&
    //   (isIOS() || !isMobileBrowser());

    // const [isCoverEnabled, setIsCoverEnabled] = useState(false);

    usePageViewLog({
      actionName: 'PageViewed',
      componentContext: 'song-v2',
      principalObjectType: 'clip',
      principalObjectValue: clip.id,
      context: { created_by: clip.user_id ?? '' },
    });

    useEffect(() => {
      if (!session || !clips || !clip) return;

      if (clip.metadata?.cover_clip_id) {
        // setIsCoverEnabled(true);
        return;
      }

      const checkFeature = async () => {
        // const isContestClip = await contestStore.isCoverEnabledOrIsContest(
        //   clip.id,
        //   clip.user_id ?? ''
        // );
        // setIsCoverEnabled(isContestClip);
      };

      checkFeature();
    }, [session, clip.id, clips]);

    useEffect(() => {
      setLiked(isLiked(clip));
    }, [clip]);

    useEffect(() => {
      setUpvoteCount(clips.clipById[clip.id]?.upvote_count);
    }, [clips.clipById[clip.id]?.upvote_count]);

    const handleLikeClick = () => {
      logWebUserEvent({
        actionName: 'LikeSongOnSongPageClicked',
        context: {
          clipId: clip.id,
          version: 'v2',
        },
      } satisfies SongPageEventType);

      // Cancel auto-open timer when user manually triggers modal
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }

      const defaultRedirectUrl = `${pathname}?${SIGNUP_SOURCE_PARAM}=${SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE}&${searchParams.toString()}`;
      openModalWithData(ModalTypes.JOIN_SUNO, {
        clipId: clip.id,
        redirectUrl: defaultRedirectUrl,
      });
      joinSunoModalShown.current = true;
    };

    const [isFollowing, setIsFollowing] = useState<boolean>(false);
    useEffect(() => {
      clips.updateClips([clip]);
      setIsFollowing(clip?.is_following_creator === true);
    }, [clip]);

    useEffect(() => {
      const storedClipTitle = getClipTitle(clips.clipById[clip.id]);
      if (storedClipTitle !== clipTitle) {
        setClipTitle(storedClipTitle);
        setNewClipTitle(storedClipTitle);
      }
      setLiked(isLiked(clips.clipById[clip.id]));
    }, [clips.clipById[clip.id]?.title, clips.clipById[clip.id]?.reaction]);

    useEffect(() => {
      // Always set the current clip on mount
      queueStore.setPlayContext({
        clips: [clip],
        contextType: ContextType.Song,
        contextId: clip.id,
      });
      playbar.clip = clip;
      playbar.setNoClipPlayCallback(() => {
        playbar.playClip(clip);
      });
      playbar.setIsClipPreloaded(true);

      setClipForSongRecs(clip);
      setAllowFlushToTop(true);
      setPreviewClip(null);
      return () => {
        setClipForSongRecs(null);
        setAllowFlushToTop(false);
      };
    }, [clip]);

    const isTablet = useBreakpointMd();
    // const isDesktop = useBreakpointXl();

    const [loading, setLoading] = useState(true);

    useEffect(() => {
      if (isTablet !== undefined) {
        setLoading(false);
      }
    }, [isTablet]);

    const handleFollow = async () => {
      logWebUserEvent({
        actionName: 'FollowArtistOnSongPageClicked',
        context: {
          clipId: clip.id,
          artistId: clip.user_id || undefined,
          version: 'v2',
        },
      } satisfies SongPageEventType);

      // Cancel auto-open timer when user manually triggers modal
      if (timerRef.current) {
        clearTimeout(timerRef.current);
        timerRef.current = null;
      }

      const defaultRedirectUrl = `${pathname}?${SIGNUP_SOURCE_PARAM}=${SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE}&${searchParams.toString()}`;
      openModalWithData(ModalTypes.JOIN_SUNO, {
        clipId: clip.id,
        redirectUrl: defaultRedirectUrl,
      });
      joinSunoModalShown.current = true;
    };

    const sunoShortType = getSunoShortType(clip);
    const isVideo =
      sunoShortType == SunoShortType.VIDEO &&
      clip.metadata?.video_to_song_video_upload_url;

    const handleAnimateCoverClick = useCallback(() => {
      openModalWithData(
        ModalTypes.GENERATE_COVER_ART,
        { clipId: clip.id, useClipCoverImage: true },
        'MobileSongPage'
      );
    }, [clip.id, openModalWithData]);

    const handleTogglePlay = () => {
      // Don't allow toggle if no clip is loaded
      if (!playbar.clip) {
        return;
      }

      logWebUserEvent({
        actionName: 'PlayCTAOnSongPageClicked',
        context: {
          clipId: clip.id,
          version: 'v2',
        },
      } satisfies SongPageEventType);

      // If this is the current song and we're trying to toggle play,
      // but audio element isn't ready, use playClip instead of togglePlay
      if (isCurrentSong && !isPlaying) {
        if (playbar.audioElement?.src === clip.audio_url) {
          playbar.togglePlay();
        } else {
          playbar.playClip(clip);
        }
        return;
      }

      queueStore.setPlayContext({
        currentIndex: 0,
        clips: queueStore.getClipsForContext(ContextType.Song, clip.id),
        contextType: ContextType.Song,
        contextId: clip.id,
      });
      playbar.playClip(clip);
    };

    const visibleStats = !isSecretStatsProfile({ handle: clip?.handle || '' });
    // const showHistoryClips =
    //   clipHistoryIds &&
    //   clipHistoryIds.length > 0 &&
    //   session.user?.id === clip.user_id;
    // const hasLineageClips =
    //   !!(clip.metadata?.cover_clip_id && isCoverEnabled) ||
    //   !!clip.metadata?.upsample_clip_id ||
    //   showHistoryClips;

    // const updateTitle = useCallback(
    //   async (title: string) => {
    //     if (clip.title === title) return;
    //     const clipId = clip.id;
    //     const result = await clips.setMetadata({
    //       clipId,
    //       title,
    //     });
    //     if (result) {
    //       if (result.success) {
    //         clip.title = title;
    //         setClipTitle(title);
    //         setNewClipTitle(title);
    //         eventLogger.logAudioActionEvent(
    //           false,
    //           ActionName.editTitle,
    //           clip,
    //           session,
    //           pathname
    //         );
    //       } else {
    //         setNewClipTitle(clipTitle);
    //       }
    //     }
    //   },
    //   [clip, clipTitle, clips, pathname, session]
    // );

    // const renderTitleContent = useCallback(
    //   ({ children: value }: { children?: string }) => {
    //     return (
    //       <TextEditable
    //         key='editableTitle'
    //         className='w-full font-semibold text-foreground-primary text-[18px]/[18px] tracking-[-0.18px]'
    //         value={value}
    //         onValueChange={setNewClipTitle}
    //         onValueCommit={updateTitle}
    //         disabled={clip.user_id !== session.userId}
    //       />
    //     );
    //   },
    //   [clip.user_id, session.userId, updateTitle]
    // );

    const isTrashed = clips.clipById[clip.id]?.is_trashed ?? false;

    // const showTwoColummLayout = isDesktop;
    // const showTabLayout = tabs.length > 1 && !showTwoColummLayout;

    // const { ref: headerRef, isIntersecting } = useIntersectionObserver();
    const { ref: headerRef } = useIntersectionObserver();

    const persona = preloadPersona || clip.persona;

    return loading ? (
      <SongPageSkeleton />
    ) : (
      <div
        className='flex w-full flex-col items-stretch overflow-hidden bg-background-primary md:px-4'
        style={dynamicHeightStyle}
      >
        <MobileSongPageHeader
          ref={headerRef}
          className=''
          contentClassName='max-md:px-4'
          title={newClipTitle}
          avatarImageUrl={clip.avatar_image_url || undefined}
          handle={clip.handle || undefined}
          displayName={clip.display_name || undefined}
          // royal_id - not needed for logged out mobile users
          {...(persona?.is_public
            ? {
                personaId: persona.id || undefined,
                personaImageUrl: persona.image_s3_id || undefined,
                personaDisplayName: persona.name || undefined,
                personaUserAvatarImageUrl: persona.user_image_url || undefined,
                personaUserHandle: persona.user_handle || undefined,
                personaUserDisplayName: persona.user_display_name || undefined,
              }
            : undefined)}
          videoUrl={
            isVideo
              ? clip.metadata?.video_to_song_video_upload_url || undefined
              : undefined
          }
          imageUrl={clip.image_url || undefined}
          tags={[
            ...tagsToArray(clip.metadata?.tags || ''),
            ...tagsToNegativeTags(
              tagsToArray(clip.metadata?.negative_tags || '')
            ),
          ]}
          caption={clip.caption || undefined}
          isSongOwner={!!(session.userId && session.userId === clip.user_id)}
          clip={clip}
          id={clip.id}
          createdAt={clip.created_at}
          clipType={clip.metadata?.type}
          modelMajorVersion={clip.major_model_version}
          modelName={clip.model_name}
          playCount={visibleStats ? clip.play_count : undefined}
          commentCount={visibleStats ? commentCount : undefined}
          likeCount={visibleStats ? upvoteCount : undefined}
          // titleContent={renderTitleContent}
          isFollowing={isFollowing}
          isLiked={liked}
          isCurrentSong={isCurrentSong}
          isTrashed={isTrashed}
          isPlaying={isPlaying}
          onImageClick={handleTogglePlay}
          onCreateClick={(prompt: string) => {
            // Cancel auto-open timer when user manually triggers modal
            if (timerRef.current) {
              clearTimeout(timerRef.current);
              timerRef.current = null;
            }

            // Build redirect URL with prompt if provided
            const params = new URLSearchParams(searchParams);
            params.set(
              SIGNUP_SOURCE_PARAM,
              SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE
            );
            if (prompt?.trim()) {
              params.set('prompt', prompt.trim());
            }
            const redirectUrl = `/create?${params.toString()}`;

            openModalWithData(ModalTypes.JOIN_SUNO, {
              clipId: clip.id,
              redirectUrl: redirectUrl,
            });
            joinSunoModalShown.current = true;

            logWebUserEvent({
              actionName: 'CreateSongOnSongPageClicked',
              context: {
                clipId: clip.id,
                prompt: prompt?.trim() || '',
                version: 'v2',
              },
            } satisfies SongPageEventType);
          }}
          onFollowClick={
            clip.user_id !== session.user?.id ? handleFollow : undefined
          }
          onPlayCountClick={handleTogglePlay}
          onCommentClick={() => {
            logWebUserEvent({
              actionName: 'CommentsOnSongPageSignUpPrompt',
              context: {
                entityId: clip.id,
                entityType: 'clip',
                numComments: commentCount,
              },
            } satisfies SongPageEventType);

            // Cancel auto-open timer when user manually triggers modal
            if (timerRef.current) {
              clearTimeout(timerRef.current);
              timerRef.current = null;
            }

            const defaultRedirectUrl = `${pathname}?${SIGNUP_SOURCE_PARAM}=${SIGNUP_SOURCE_VALUES.MOBILE_SONG_PAGE}&${searchParams.toString()}`;
            openModalWithData(ModalTypes.JOIN_SUNO, {
              clipId: clip.id,
              redirectUrl: defaultRedirectUrl,
            });
            joinSunoModalShown.current = true;
            // logWebUserEvent({
            //   actionName: 'CommentsOnSongPageClicked',
            //   context: {
            //     clipId: clip.id,
            //     numComments: commentCount,
            //     version: 'v2',
            //   },
            // } satisfies SongPageEventType);
            // setCurrentTab('comments');
          }}
          onLikeClickForAnonymousUser={handleLikeClick}
          onShareClick={async () => {
            await shareClip(clips.apiClient, clip);
            logWebUserEvent({
              actionName: 'ShareSongOnSongPageClicked',
              context: {
                isMobile: isMobileBrowser(),
                version: 'v2',
              },
            });
          }}
          onPlayClick={handleTogglePlay}
          onAnimateCoverClick={handleAnimateCoverClick}
        >
          <></>
        </MobileSongPageHeader>
      </div>
    );
  }
);

export default MobileSongPage;
